package com.maxeky.sso.controller;


import com.maxeky.sso.domain.R;

import com.alibaba.fastjson2.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

@Slf4j
@RestController
public class ThirdController {


    @Value("${security.oauth2.client.token-uri}")
    private String tokenUrl;
    @Value(("${security.oauth2.client.client-id}"))
    private String clientId;
    @Value(("${security.oauth2.client.client-secret}"))
    private String clientSecret;
    @Value(("${security.oauth2.client.grant-type}"))
    private String grantType;
    @Value("${security.oauth2.client.redirect_uri}")
    private String redirectUrl;
    @Value("${security.oauth2.resource.user-info-uri}")
    private String userInfoUrl;

    /**
     * 回调单点登录接口，查询用户登录账号信息、角色信息，并实现业务系统端的用户登录
     * @param code
     * @param state
     * @return
     */
    @GetMapping("/sso/callback")
    public R<?> callback(@RequestParam("code")String code, @RequestParam(value = "state",required = false)String state) {
        RestTemplate restTemplate = new RestTemplate();
        // 发送请求获取用户信息
        String url = tokenUrl+"?code="+code+"&client_id="+clientId+"&client_secret="+clientSecret+"&grant_type="+grantType+"&redirect_uri="+redirectUrl;

        ResponseEntity<JSONObject> tokenRes = restTemplate.getForEntity(url, JSONObject.class);

        String token = tokenRes.getBody().getString("access_token");
        String userUrl = userInfoUrl+"?access_token="+token;
        ResponseEntity<JSONObject> userRes = restTemplate.getForEntity(userUrl, JSONObject.class);
        Map<String,Object> tokenMap = null;
        // 根据用户登录账号，实现业务系统端的用户登录
//        LoginUser userInfo = remoteUserService.getUserInfo(userRes.getBody().getString("username"), SecurityConstants.INNER);
//        Map<String,Object> tokenMap= tokenService.createToken(userInfo);
        return R.ok(tokenMap);
    }
}
